import time
import threading
import pygame
from BrainLinkParser import BrainLinkParser  # 请确保已按官方说明放置 .pyd 文件

# ============== 配置 ==============
COM_PORT = "COM5"          # ←←← 改成你的 Brainlink Pro 实际串口号（设备管理器查看）

# 准备简单钢琴音（你需要下载几个短钢琴音文件）
# 这里用不同音高的 C大调音符作为示例
# 下载地址建议：搜索 "free piano soundfont wav" 或用下面映射

pygame.mixer.init(frequency=44100, size=-16, channels=2, buffer=512)
pygame.mixer.set_num_channels(8)   # 支持同时多个音

# 预加载几个钢琴音（请提前准备这些 wav 文件放到脚本同目录）
# 你可以从网上下载单音 wav（如 C4.wav, E4.wav 等），或我后面教你用更简单方式
sounds = {
    60: pygame.mixer.Sound("C4.wav"),   # 中音 Do
    64: pygame.mixer.Sound("E4.wav"),   # Mi
    67: pygame.mixer.Sound("G4.wav"),   # Sol
    72: pygame.mixer.Sound("C5.wav"),   # 高音 Do
    48: pygame.mixer.Sound("C3.wav"),   # 低音 Do
}

# ============== Brainlink 回调 ==============
def on_brainlink_data(data):
    attention = data.get('attention', 0)
    meditation = data.get('meditation', 0)
    blink = data.get('blink', 0)

    print(f"专注度: {attention:3d} | 放松度: {meditation:3d} | 眨眼: {blink}")

    if attention > 65:                      # 专注 → 明亮较高音
        note = [60, 64, 67, 72][attention % 4]
        vol = min(1.0, 0.6 + (attention - 65) * 0.01)
        if note in sounds:
            sounds[note].set_volume(vol)
            sounds[note].play()

    elif meditation > 55:                   # 放松 → 柔和较低音 + 长音
        note = [48, 52, 55, 60][meditation % 4]
        if note in sounds:
            sounds[note].set_volume(0.7)
            sounds[note].play(maxtime=800)   # 稍长一点的声音

    if blink > 70:                          # 眨眼 → 强音强调
        if 72 in sounds:
            sounds[72].set_volume(1.0)
            sounds[72].play()

# ============== 启动 Brainlink ==============
parser = BrainLinkParser()   # 根据你实际的 BrainLinkParser 用法调整

def read_brainlink():
    try:
        # 具体启动方式请参考官方 GitHub 示例，通常是：
        parser.start(COM_PORT, 115200)
        print("✅ Brainlink Pro 已连接！戴上头环用意念弹钢琴吧 🎹")
    except Exception as e:
        print("启动失败:", e)

threading.Thread(target=read_brainlink, daemon=True).start()

print("程序已启动，按 Ctrl+C 退出")

try:
    while True:
        time.sleep(0.05)
except KeyboardInterrupt:
    pygame.mixer.quit()
    print("\n已停止演奏")